package com.hjm.mall.config.handler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class JsonListMapTypeHandler extends BaseTypeHandler<List<Map<String, Integer>>> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Map<String, Integer>> parameter, JdbcType jdbcType) throws SQLException {
        // 将List<Map<String, Integer>>转换为JSON字符串并设置到PreparedStatement中
        String json = objectMapper.writeValueAsString(parameter);
        ps.setString(i, json);
    }

    @Override
    public List<Map<String, Integer>> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        if (json == null) {
            return null;
        }
        try {
            // 从JSON字符串中解析List<Map<String, Integer>>
            TypeReference<List<Map<String, Integer>>> typeRef = new TypeReference<List<Map<String, Integer>>>() {};
            return objectMapper.readValue(json, typeRef);
        } catch (Exception e) {
            throw new SQLException("JSON转化成List失败 <Map<String, Integer>>", e);
        }
    }

    @Override
    public List<Map<String, Integer>> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getNullableResult(rs, rs.getMetaData().getColumnName(columnIndex));
    }

    @Override
    public List<Map<String, Integer>> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getNullableResult(cs.getResultSet(), columnIndex);
    }
}
